<template>
    <div id="User">
        <article>
            <h2>文章管理</h2>
            <el-tabs v-model="activeName" type="card">
                <el-tab-pane label="我的文章" name="first">
                    <el-table :data="tableData" style="width: 100%">
                        <el-table-column label="标题" prop="title">
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template #default="scope">
                                <el-button
                                    size="mini"
                                    type="warning"
                                    @click="handleEdit(scope.$index, scope.row)"
                                    >修改</el-button
                                >
                                <el-button
                                    size="mini"
                                    type="danger"
                                    @click="
                                        handleDelete(scope.$index, scope.row)
                                    "
                                    >删除</el-button
                                >
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="添加文章" name="second">
                    <el-form
                        :model="articleInfo"
                        ref="articleInfoRef"
                        label-width="100px"
                    >
                        <el-form-item label="文章标题">
                            <el-input
                                type="text"
                                v-model="articleInfo.title"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="文章类型">
                            <el-select v-model="articleInfo.category">
                                <el-option
                                    v-for="item in categoryList"
                                    :key="item.id"
                                    :label="item.category"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="文章封面">
                            <el-upload
                                class="avatar-uploader"
                                :action="`${baseURL}/imageUpload?type=cover`"
                                :headers="headers"
                                :show-file-list="false"
                                :with-credentials="true"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                            >
                                <img
                                    v-if="imageUrl"
                                    :src="imageUrl"
                                    class="avatar"
                                />
                                <i
                                    v-else
                                    class="el-icon-plus avatar-uploader-icon"
                                ></i>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="文章内容">
                            <WangEditor
                                @editor:created="initCreateRef"
                                v-model="articleInfo.content"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleSubmitForm"
                                >确认发布</el-button
                            >
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="修改文章" name="third">
                    <el-form
                        :model="selectedArticle"
                        ref="selectedArticleRef"
                        label-width="100px"
                    >
                        <el-form-item label="文章标题">
                            <el-input
                                type="text"
                                v-model="selectedArticle.title"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="文章类型">
                            <el-select v-model="selectedArticle.category">
                                <el-option
                                    v-for="item in categoryList"
                                    :key="item.id"
                                    :label="item.category"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="文章封面">
                            <el-upload
                                class="avatar-uploader"
                                :action="`${baseURL}/imageUpload?type=cover`"
                                :headers="headers"
                                :show-file-list="false"
                                :with-credentials="true"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                            >
                                <img
                                    v-if="imageUrl"
                                    :src="imageUrl"
                                    class="avatar"
                                />
                                <i
                                    v-else
                                    class="el-icon-plus avatar-uploader-icon"
                                ></i>
                            </el-upload>
                        </el-form-item>

                        <el-form-item label="文章内容">
                            <WangEditor
                                ref="editor"
                                @editor:created="initEditRef"
                                v-model="selectedArticle.content"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleUpdateForm"
                                >保存更改</el-button
                            >
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </article>
    </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { shallowRef } from "vue";
import WangEditor from "../components/WangEditor.vue";

export default {
    name: "User",
    components: {
        WangEditor,
    },
    data() {
        return {
            imageUrl: "../assets/imgs/1.jpg",
            baseURL: "http://localhost:8081/ts/article/api",
            headers: { token: localStorage.getItem("token") || "" },
            tableData: [],
            activeName: "first",
            categoryList: [
                {
                    id: 1,
                    value: "0",
                    category: "游记",
                },
                {
                    id: 2,
                    value: "1",
                    category: "攻略",
                },
            ],
            articleInfo: {
                title: "",
                category: "0",
                content: "",
            },
            selectedArticle: {
                title: "",
                content: "",
                serial: "",
                category: "0",
            },
            imageUrl: "",
            editorRef: {
                create: null,
                edit: null,
            },
        };
    },
    computed: {
        ...mapState(["userInfo"]),
    },
    methods: {
        ...mapMutations(["userUpdate", "updateUser"]),
        //上传成功的回调
        handleAvatarSuccess(res, file) {
            console.log(res);
            console.log(file);
            this.imageUrl = URL.createObjectURL(file.raw);
            this.articleInfo.cover = res.data;
            if (res.code) {
                return this.$message.error(res.msg);
            }

            console.log(res);

            //提示
            this.$message.success("封面上传成功！");
            //更新vuex数据
            // this.updateUser(res.respData.userInfo);
        },

        //上传之前的回调
        beforeAvatarUpload(file) {
            let fileType = file.type;
            const isLt2M = file.size / 1024 / 1024 < 2;
            const isJPG = /^image\/(jpeg|png)$/.test(fileType);

            if (!isJPG) {
                this.$message.error("封面图片只能是 JPG,PNG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("封面图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },
        initCreateRef(editor) {
            this.editorRef.create = editor;
        },
        initEditRef(editor) {
            this.editorRef.edit = editor;
        },

        handleEdit(index, row) {
            console.log(row);
            this.selectedArticle = {
                category: row.type.toString(),
                title: row.title,
                content: row.content,
                serial: row.serial,
                cover: row.cover,
            };
            //复制imageUrl
            this.imageUrl = row.cover;
            if (!!this.editorRef.edit) {
                this.editorRef.edit.setHtml(row.content);
                this.activeName = "third";
            } else {
                return false;
            }
        },

        handleDelete(index, row) {
            this.$axios({
                method: "get",
                headers: { token: localStorage.getItem("token") || "" },
                url: `http://localhost:8081/ts/article/deletearticle?articleId=${row.serial}`,
            }).then((res) => {
                this.updateArticles();
            });
        },

        handleUpdateForm: function () {
            console.log(this.selectedArticle);
            let forms = new FormData();
            forms.append("title", this.selectedArticle.title);
            forms.append("type", parseInt(this.selectedArticle.category));
            forms.append("content", this.selectedArticle.content);
            forms.append("articleId", this.selectedArticle.serial);
            forms.append("cover", this.imageUrl);
            const titleValid =
                this.selectedArticle.title.length &&
                this.selectedArticle.title.length <= 20;
            const contentValid =
                this.selectedArticle.content.length &&
                this.selectedArticle.content.length <= 10000;
            const valid = titleValid && contentValid;
            console.log(forms);
            if (valid) {
                this.$axios({
                    method: "post",
                    headers: {
                        token: localStorage.getItem("token") || "",
                        "Content-Type": "multipart/form-data",
                    },
                    url: `http://localhost:8081/ts/article/modifyArticle`,
                    data: forms,
                }).then(() => {
                    this.$message({
                        message: "修改成功",
                        type: "success",
                    });
                    this.updateArticles();
                    this.activeName = "first";
                });
            } else {
                if (!titleValid)
                    this.$message.error("标题不能为空且不能超过20个字符");
                if (!contentValid)
                    this.$message.error("内容不能为空且不能超过10000个字符");
            }
        },

        handleSubmitForm: function () {
            console.log(this.articleInfo);
            console.log(this.imageUrl);
            let forms = new FormData();
            forms.append("title", this.articleInfo.title);
            forms.append("category", this.articleInfo.category);
            forms.append("content", this.articleInfo.content);
            forms.append("cover", this.articleInfo.cover.url);

            const titleValid =
                this.articleInfo.title.length &&
                this.articleInfo.title.length <= 20;
            const contentValid =
                this.articleInfo.content.length &&
                this.articleInfo.content.length <= 10000;
            const valid = titleValid && contentValid;
            if (valid) {
                this.$axios({
                    method: "post",
                    headers: {
                        token: localStorage.getItem("token") || "",
                        "Content-Type": "multipart/form-data",
                    },
                    url: `http://localhost:8081/ts/article/publish`,
                    data: forms,
                }).then(() => {
                    this.$message({
                        message: "发布成功",
                        type: "success",
                    });
                    this.updateArticles();
                    this.activeName = "first";
                });
            } else {
                if (!titleValid)
                    this.$message.error("标题不能为空且不能超过20个字符");
                if (!contentValid)
                    this.$message.error("内容不能为空且不能超过10000个字符");
            }
        },

        updateArticles() {
            this.$axios({
                method: "get",
                headers: { token: localStorage.getItem("token") || "" },
                url: `http://localhost:8081/ts/user/personalHomePageRelated?userId=${this.$store.state.userInfo.serial}`,
            }).then((res) => {
                this.tableData = JSON.parse(res.data.respData.allarticle);
                //   this.Info = JSON.parse(res.data.respData.user)
                //   if (res.data.respData.isFollowed) this.isFollowEd = res.data.respData.isFollowed
            });
        },
    },

    created() {
        this.updateArticles();
        console.log(this.$store.state.userInfo);
        //如果是商家，文章类型添加一个广告
        if (
            this.$store.state.userInfo.isSeller &&
            this.$store.state.userInfo.isSeller === 1
        ) {
            this.categoryList.push({ id: 3, value: "3", category: "广告" });
        }
    },
};
</script>

<style lang="less" scoped>
#User {
    flex: 1;

    article {
        border-radius: 15px;
        box-sizing: border-box;
        width: 100%;
        margin-bottom: 15px;
        box-shadow: 0 0 4px #ddd;
        padding: 25px 20px;
        background-color: #fff;

        h2 {
            margin-bottom: 15px;
            font-size: 20px;
            letter-spacing: 3px;
            line-height: 24px;
            border-left: 5px solid #73b899;
            text-indent: 10px;
        }
    }

    /deep/ .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        margin-top: 10px;
    }
    /deep/ .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }
    /deep/ .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    /deep/ .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
}
</style>
